package com.yxb.cms.service;

import com.yxb.cms.architect.constant.BussinessCode;
import com.yxb.cms.architect.utils.BussinessMsgUtil;
import com.yxb.cms.dao.CoursesMapper;
import com.yxb.cms.dao.TeachCourseMapper;
import com.yxb.cms.dao.TeachersMapper;
import com.yxb.cms.dao.expmle.CoursesExample;
import com.yxb.cms.domain.bo.BussinessMsg;
import com.yxb.cms.domain.bo.ExcelExport;
import com.yxb.cms.domain.vo.*;
import com.yxb.cms.enums.YesOrNo;
import org.apache.ibatis.annotations.Param;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CoursesService {
    private Logger log = LogManager.getLogger(CoursesService.class);

    @Autowired
    private CoursesMapper coursesMapper;

    @Autowired
    private ClassesService classesService;

    @Autowired
    private TeachersMapper teachersMapper;

    @Autowired
    private TeachCourseMapper teachCourseMapper;

    /**
     * 插入课程
     * @param teachers 课程实体
     */
    @Transactional
    public BussinessMsg insertCourses(Courses courses, String currUserName){

        try {
            Date now = new Date();
            courses.setCourseCode(generateCoursesCode());
            courses.setCreateTime(now);
            courses.setCreator(currUserName);
            courses.setUpdateTime(now);
            courses.setModifier(currUserName);
            courses.setDeleteFlage(YesOrNo.NO.getValue());
            coursesMapper.insertSelective(courses);
        } catch (Exception e) {
            log.error("保存课程信息方法内部错误",e);
            throw e;
        }
        return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_SUCCESS);
    }

    /**
     * 更新课程
     * @param teachers 课程实体
     */
    @Transactional
    public BussinessMsg updateByPrimaryKeySelective(Courses courses, String currUserName){
        try {
            courses.setUpdateTime(new Date());
            courses.setModifier(currUserName);
            coursesMapper.updateByPrimaryKeySelective(courses);
        } catch (Exception e) {
            log.error("保存课程信息方法内部错误",e);
            throw e;
        }
        return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_SUCCESS);
    }

    /**
     * 查询课程
     * @param tid 课程ID
     */
    public Courses queryCoursessByCoursess(Long cid){
        //systemLogMapper.updateByPrimaryKeySelective(systemLog);
        Courses courses = coursesMapper.selectByPrimaryKey(cid);
        return courses;
    }

    /**
     * 删除课程
     * @param tid 课程ID
     */
    @Transactional
    public BussinessMsg deleteByPrimaryKeySelective(Long cid){
        try {
            Courses courses = new Courses();
            courses.setDeleteFlage(YesOrNo.YES.getValue());
            courses.setId(cid);
            coursesMapper.updateByPrimaryKeySelective(courses);
        } catch (Exception e) {
            log.error("删除课程信息方法内部错误",e);
            throw e;
        }
        return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_SUCCESS);
    }


    /**
     * 课程信息分页显示
     * @param teachers 课程实体
     * @return
     */
    public String selectCoursesPageList(Courses courses){

        List<Courses> CoursessList = coursesMapper.selectCoursesPage(courses);

        Long count = coursesMapper.countByExample(courses);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        map.put("data", CoursessList);

        return Json.toJson(map);
    }

    public List<Courses> queryAllClasses(){
        Courses courses = new Courses();
        List<Courses> coursesList = coursesMapper.selectCoursesPage(courses);
        return coursesList;
    }

    /**
     * 业务日志EXCEL导出
     * @param systemLog 日志实体
     * @return
     */
    public ExcelExport excelExportSystemLogList(SystemLog systemLog){
        ExcelExport excelExport = new ExcelExport();
        List<SystemLog> systemLogList = null;//systemLogMapper.selectSystemLogList(systemLog);
        excelExport.addColumnInfo("日志标题","logTitle");
        excelExport.addColumnInfo("日志类型","logType_Lable");
        excelExport.addColumnInfo("日志请求URL","logUrl");
        excelExport.addColumnInfo("请求方式","logMethod");
        excelExport.addColumnInfo("请求参数","logParams");
        excelExport.addColumnInfo("请求用户","logUserName");
        excelExport.addColumnInfo("请求IP","logIp");
        excelExport.addColumnInfo("IP归属","logIpAddress");
        excelExport.addColumnInfo("请求时间","logStartTime_Lable");
        excelExport.addColumnInfo("耗时(毫秒)","logElapsedTime");


        excelExport.setDataList(systemLogList);
        return excelExport;
    }


    /**
     * 异常日志EXCEL导出
     * @param systemLog 日志实体
     * @return
     */
    public ExcelExport excelExportSysExceptionLogList(SystemLog systemLog){
        ExcelExport excelExport = new ExcelExport();
        List<SystemLog> systemLogList = null;//systemLogMapper.selectSystemLogList(systemLog);
        excelExport.addColumnInfo("日志标题","logTitle");
        excelExport.addColumnInfo("日志类型","logType_Lable");
        excelExport.addColumnInfo("异常方法","logUrl");
        excelExport.addColumnInfo("请求参数","logParams");
        excelExport.addColumnInfo("异常信息","logException");
        excelExport.addColumnInfo("请求用户","logUserName");
        excelExport.addColumnInfo("请求IP","logIp");
        excelExport.addColumnInfo("IP归属","logIpAddress");
        excelExport.addColumnInfo("请求时间","logStartTime_Lable");
        excelExport.addColumnInfo("耗时(毫秒)","logElapsedTime");


        excelExport.setDataList(systemLogList);
        return excelExport;
    }

    //获取课程编号
    private String generateCoursesCode(){
        return "COURSES"+new Date().getTime();
    }

    /**
     * 排课
     * */
    public String getWork(){
        List<Work> works = coursesMapper.selectWork();

        List<Classes> classes = classesService.queryAllClasses();
        int i = 0;
        for (Work work:works) {
            for (Work work2:works) {
                if(work.getClassTime().equals(work2.getClassTime()) &&
                        work.getSeveralSections().equals(work2.getSeveralSections())){
                        i++;
                        if(i==2){
                            work.setClassName(classes.get(i).getClassName());
                        }
                }
            }
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",works.size());
        map.put("data", works);

        return Json.toJson(map);
    }

    List<ClassTeach> classTeaches = new ArrayList<>();

    /**
     * 排课V2
     * */
    public String getWorkV2(Long classId){

        Map<String, Object> map = new HashMap<String, Object>();

        //删除班级下的课程表
        coursesMapper.deleteCurriculumByClassId(classId,0);

        //查询课程下面是否有老师
        classTeaches = teachersMapper.selectClassTeachById(classId);
        if(classTeaches.size() <= 3 ){
            map.put("code",0);
            map.put("msg","该班级老师数量不够");
            return Json.toJson(map);
        }
        List<Long> courseIds = coursesMapper.selectCourse();
        /*List<Long> teachIds = new ArrayList<>();
        for (ClassTeach classTeach:classTeaches) {
            teachIds.add(classTeach.getId());
        }*/
        Random rand = new Random();
        Map<Long,Object> tmap = new HashMap<>();
        Map<Long,Courses> tmap2 = new HashMap<>();

        EachSession eachOne = new EachSession();
        EachSession eachTwo = new EachSession();
        EachSession eachThree = new EachSession();
        EachSession eachFour = new EachSession();
        EachSession eachFive = new EachSession();
        EachSession eachSix = new EachSession();
        EachSession eachSeven = new EachSession();
        EachSession eachEight = new EachSession();

        //查看管理关系表中是否存在此时间和老师
        for (Long courseId:courseIds) {
            ClassTeach classTeach = classTeaches.get(rand.nextInt(classTeaches.size()));
            queryCourseMap(courseId,classTeach.getId(), classTeaches,tmap,tmap2);
            coursesMapper.insertCurriculum(courseId,classTeach.getId(),0,classId);
        }
        for (Long courseId:courseIds) {

            Long classTeachId = (Long)tmap.get(courseId);
            //查询星期一星期二这样的课程
            CourseTime courseTime = coursesMapper.selectCourseTimeById(courseId);
            ClassTeach classTeach = teachersMapper.selectClassTeachByIdV2(classTeachId);
            if("第一节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachOne,classTeach);
            }else if("第二节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachTwo,classTeach);
            }else if("第三节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachThree,classTeach);
            }else if("第四节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachFour,classTeach);
            }else if("第五节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachFive,classTeach);
            }else if("第六节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachSix,classTeach);
            }else if("第七节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachSeven,classTeach);
            }else if("第八节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachEight,classTeach);
            }
        }
        ArrayList<EachSession> eachSessions = new ArrayList<>();
        eachSessions.add(eachOne);
        eachSessions.add(eachTwo);
        eachSessions.add(eachThree);
        eachSessions.add(eachFour);
        eachSessions.add(eachFive);
        eachSessions.add(eachSix);
        eachSessions.add(eachSeven);
        eachSessions.add(eachEight);

        map.put("code",0);
        map.put("msg","");
        map.put("count",eachSessions.size());
        map.put("data", eachSessions);
        return Json.toJson(map);
    }

    private void queryCourseMap(Long courseId,Long classTeachId,List<ClassTeach> classTeachList,Map<Long,Object> map,Map<Long,Courses> map2){
        Long culumCount = coursesMapper.selectCurriculum(courseId, classTeachId);

        if(null == culumCount){
            Map<String,SourceNumber> stringIntegerMap = querySourceByMap(map,map2);
            SourceNumber meishu = stringIntegerMap.get("meishu");
            SourceNumber tiyu = stringIntegerMap.get("tiyu");
            SourceNumber diannao = stringIntegerMap.get("diannao");
            SourceNumber yinyue = stringIntegerMap.get("yinyue");
            SourceNumber zhengzhi = stringIntegerMap.get("zhengzhi");
            SourceNumber lishi = stringIntegerMap.get("lishi");
            SourceNumber dili = stringIntegerMap.get("dili");
            SourceNumber wuli = stringIntegerMap.get("wuli");
            SourceNumber huaxue = stringIntegerMap.get("huaxue");
            SourceNumber shengwu = stringIntegerMap.get("shengwu");

            if(meishu.getNumber().intValue()==2){
                if(getRemoveIndex(meishu.getClassTeach())>0){
                    classTeachList.remove(getRemoveIndex(meishu.getClassTeach()));
                }
            }
            if(tiyu.getNumber().intValue()==2){
                if(getRemoveIndex(tiyu.getClassTeach())>0) {
                    classTeachList.remove(getRemoveIndex(tiyu.getClassTeach()));
                }
            }
            if(diannao.getNumber().intValue()==2){
                if(getRemoveIndex(diannao.getClassTeach())>0) {
                    classTeachList.remove(getRemoveIndex(diannao.getClassTeach()));
                }
            }
            if(yinyue.getNumber().intValue()==2){
                if(getRemoveIndex(yinyue.getClassTeach())>0) {
                    classTeachList.remove(getRemoveIndex(yinyue.getClassTeach()));
                }
            }
            if(zhengzhi.getNumber().intValue()==3){
                if(getRemoveIndex(zhengzhi.getClassTeach())>0) {
                    classTeachList.remove(getRemoveIndex(zhengzhi.getClassTeach()));
                }
            }
            if(lishi.getNumber().intValue()==3){
                if(getRemoveIndex(lishi.getClassTeach())>0) {
                    classTeachList.remove(getRemoveIndex(lishi.getClassTeach()));
                }
            }
            if(dili.getNumber().intValue()==3){
                if(getRemoveIndex(dili.getClassTeach())>0) {
                    classTeachList.remove(getRemoveIndex(dili.getClassTeach()));
                }
            }
            if(wuli.getNumber().intValue()==3){
                if(getRemoveIndex(wuli.getClassTeach())>0) {
                    classTeachList.remove(getRemoveIndex(wuli.getClassTeach()));
                }
            }
            if(huaxue.getNumber().intValue()==3){
                if(getRemoveIndex(huaxue.getClassTeach())>0) {
                    classTeachList.remove(getRemoveIndex(huaxue.getClassTeach()));
                }
            }
            if(shengwu.getNumber().intValue()==3){
                if(getRemoveIndex(shengwu.getClassTeach())>0) {
                    classTeachList.remove(getRemoveIndex(shengwu.getClassTeach()));
                }
            }

            map.put(courseId,classTeachId);
            ClassTeach classTeach = teachersMapper.selectClassTeachByIdV2(classTeachId);
            //通过教师id查询出课程
            Teachers teachers = teachersMapper.selectByPrimaryKey(classTeach.getTeachId());
            //课程
            Courses courses = coursesMapper.selectByPrimaryKey(teachers.getCourseId());
            map2.put(courseId,courses);
        }else {
            Random rand = new Random();
            ClassTeach classTeach = classTeachList.get(rand.nextInt(classTeachList.size()));
            queryCourseMap(courseId,classTeach.getId(),classTeachList, map,map2);
        }
    }

    private void setEachSession(CourseTime courseTime,EachSession eachOne, ClassTeach classTeach){

        //通过教师id查询出课程
        Teachers teachers = teachersMapper.selectByPrimaryKey(classTeach.getTeachId());
        //课程
        Courses courses = coursesMapper.selectByPrimaryKey(teachers.getCourseId());

        if("星期一".equals(courseTime.getWeek())){
            eachOne.setMonday(courses.getName()+"("+teachers.getTname()+")");
        }else if("星期二".equals(courseTime.getWeek())){
            eachOne.setTuesday(courses.getName()+"("+teachers.getTname()+")");
        }else if("星期三".equals(courseTime.getWeek())){
            eachOne.setWednesday(courses.getName()+"("+teachers.getTname()+")");
        }else if("星期四".equals(courseTime.getWeek())){
            eachOne.setThursday(courses.getName()+"("+teachers.getTname()+")");
        }else if("星期五".equals(courseTime.getWeek())){
            eachOne.setFriday(courses.getName()+"("+teachers.getTname()+")");
        }

    }


    public String queryCurriculum(Long classId){
        Map<String, Object> map = new HashMap<String, Object>();
        List<Curriculum> curricula = coursesMapper.selectCurriculumByClassId(classId);
        if(curricula.size()<=0){
            map.put("code",0);
            map.put("msg","该班级无课程");
            map.put("count",0);
            map.put("data", new ArrayList<>());
            return Json.toJson(map);
        }
        EachSession eachOne = new EachSession();
        EachSession eachTwo = new EachSession();
        EachSession eachThree = new EachSession();
        EachSession eachFour = new EachSession();
        EachSession eachFive = new EachSession();
        EachSession eachSix = new EachSession();
        EachSession eachSeven = new EachSession();
        EachSession eachEight = new EachSession();

        for (Curriculum curriculum:curricula) {

            //查询星期一星期二这样的课程
            CourseTime courseTime = coursesMapper.selectCourseTimeById(curriculum.getTimeId());
            ClassTeach classTeach = teachersMapper.selectClassTeachByIdV2(curriculum.getClasTeachId());
            if("第一节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachOne,classTeach);
            }else if("第二节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachTwo,classTeach);
            }else if("第三节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachThree,classTeach);
            }else if("第四节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachFour,classTeach);
            }else if("第五节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachFive,classTeach);
            }else if("第六节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachSix,classTeach);
            }else if("第七节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachSeven,classTeach);
            }else if("第八节".equals(courseTime.getSection())){
                setEachSession(courseTime,eachEight,classTeach);
            }
        }
        ArrayList<EachSession> eachSessions = new ArrayList<>();
        eachSessions.add(eachOne);
        eachSessions.add(eachTwo);
        eachSessions.add(eachThree);
        eachSessions.add(eachFour);
        eachSessions.add(eachFive);
        eachSessions.add(eachSix);
        eachSessions.add(eachSeven);
        eachSessions.add(eachEight);

        map.put("code",0);
        map.put("msg","");
        map.put("count",eachSessions.size());
        map.put("data", eachSessions);
        return Json.toJson(map);
    }


    public String saveCurriculum(Long classId){
        Map<String, Object> map = new HashMap<String, Object>();
        coursesMapper.deleteCurriculumByClassId(classId,1);
        coursesMapper.updateCurriculumByClassId(classId);
        map.put("code",200);
        map.put("msg","");
        return Json.toJson(map);
    }


    private Map<String,SourceNumber> querySourceByMap(Map<Long,Object> map,Map<Long,Courses> map2){
        Map<String,SourceNumber> rustMap = new HashMap<>();

        int meishu = 0;
        int tiyu = 0;
        int diannao = 0;
        int yinyue = 0;
        int zhengzhi = 0;
        int lishi = 0;
        int dili = 0;
        int wuli = 0;
        int huaxue = 0;
        int shengwu = 0;
        SourceNumber meishuObj = new SourceNumber();
        SourceNumber tiyuObj = new SourceNumber();
        SourceNumber diannaoObj = new SourceNumber();
        SourceNumber yinyueObj = new SourceNumber();
        SourceNumber zhengzhiObj = new SourceNumber();
        SourceNumber lishiObj = new SourceNumber();
        SourceNumber diliObj = new SourceNumber();
        SourceNumber wuliObj = new SourceNumber();
        SourceNumber huaxueObj = new SourceNumber();
        SourceNumber shengwuObj = new SourceNumber();

        for (Long key : map2.keySet()) {
                //System.out.println("Value = " + value);
            ClassTeach classTeach = teachersMapper.selectClassTeachByIdV2(Long.valueOf(map.get(key).toString()));
            if("美术".equals(map2.get(key).getName())){
                    meishu++;
                meishuObj.setClassTeach(classTeach);
                }else if("体育".equals(map2.get(key).getName())){
                    tiyu++;
                tiyuObj.setClassTeach(classTeach);
                }else if("电脑".equals(map2.get(key).getName())){
                    diannao++;
                diannaoObj.setClassTeach(classTeach);
                }else if("音乐".equals(map2.get(key).getName())){
                    yinyue++;
                yinyueObj.setClassTeach(classTeach);
                }else if("政治".equals(map2.get(key).getName())){
                    zhengzhi++;
                zhengzhiObj.setClassTeach(classTeach);
                }else if("历史".equals(map2.get(key).getName())){
                    lishi++;
                lishiObj.setClassTeach(classTeach);
                }else if("地理".equals(map2.get(key).getName())){
                    dili++;
                diliObj.setClassTeach(classTeach);
                }else if("物理".equals(map2.get(key).getName())){
                    wuli++;
                wuliObj.setClassTeach(classTeach);
                }else if("化学".equals(map2.get(key).getName())){
                    huaxue++;
                    huaxueObj.setClassTeach(classTeach);
                }else if("生物".equals(map2.get(key).getName())){
                    shengwu++;
                    shengwuObj.setClassTeach(classTeach);
                }

            }

        meishuObj.setNumber(meishu);
        tiyuObj.setNumber(tiyu);
        diannaoObj.setNumber(diannao);
        yinyueObj.setNumber(yinyue);
        zhengzhiObj.setNumber(zhengzhi);
        lishiObj.setNumber(lishi);
        diliObj.setNumber(dili);
        wuliObj.setNumber(wuli);
        huaxueObj.setNumber(huaxue);
        shengwuObj.setNumber(shengwu);
        rustMap.put("meishu",meishuObj);
        rustMap.put("tiyu",tiyuObj);
        rustMap.put("diannao",diannaoObj);
        rustMap.put("yinyue",yinyueObj);
        rustMap.put("zhengzhi",zhengzhiObj);
        rustMap.put("lishi",lishiObj);
        rustMap.put("dili",diliObj);
        rustMap.put("wuli",wuliObj);
        rustMap.put("huaxue",huaxueObj);
        rustMap.put("shengwu",shengwuObj);

        return rustMap;
    }


    private int getRemoveIndex(ClassTeach classTeach){
        int  i = 0;
        for (ClassTeach teach:classTeaches) {

            if(teach.getId().intValue()==classTeach.getId().intValue()){
                return i;
            }
            i++;
        }
        return -1;
    }

}